package com.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/photo")
@CrossOrigin //解决跨域访问问题，
public class PhotoController {

    @Value("D:/WorkPlace/毕设选题线上小程序/imgs")    //此处为在配置文件中写的本地路径
    private String PhotoPath;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public String upload(MultipartFile file){
        System.out.println(file);
        String originalFilename = file.getOriginalFilename();

//        根据最后一个.的索引来截取后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString()+substring;
        File dir = new File(PhotoPath);
        if (!dir.exists()){
            dir.mkdir();
        }
        try {
            file.transferTo(new File(PhotoPath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //获取图片文件
            FileInputStream inputStream = new FileInputStream(new File(PhotoPath+name));
            //输出流
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            System.out.println("无该图片！");
//            e.printStackTrace();
        }

    }
}

